
import { Message } from 'element-ui';
import store from '../../../store';

const commonFn = {
    jsonToString(obj) {
      return JSON.stringify(obj)
    },
    deepClone(obj) {
      return JSON.parse(this.jsonToString(obj))
    },
    putCacheData(key, value ,timeout){
      let _value = {};
      _value.value = value;
      if(timeout){
        _value.timeout = timeout;
        _value.timestamp = new Date().getTime();
      }
      store.dispatch('cache/setCacheData', {key : key , value : _value});
    },
    getCacheData(key){
      
      let _value = store.state.cache.cacheData[key];
      if(_value && _value.timeout) { 
        let cur = new Date().getTime();
        let diff = cur - _value.timestamp;
        if(diff > _value.timeout) {
          this.removeCacheData(key);
          return null;
        } else {
          return _value.value;
        }
      } else if(_value) {
        return _value.value;
      } else {
        return null;
      }
    },
    removeCacheData(key){
      let value = store.state.cache.cacheData[key];
      if(value){
          store.dispatch('cache/removeCacheData', key);
      }
      return value;
    },
    toastMsg(type, msg) {
      switch (type) {
        case 'normal':
          Message.info(msg);
          break
        case 'success':
          Message.success(msg);
          break
        case 'warning':
          Message.warning(msg)
          break
        case 'error':
          Message.error(msg)
          break
      }
  },
}

export default commonFn
